<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" class="layerPublicStyle">
    <uni-forms-item name="sn">
      <lay-form-item label="编号SN"  class="_row_style">
          <lay-input v-model="formData.sn"></lay-input>
      </lay-form-item>
    </uni-forms-item>

    <uni-forms-item name="key">
      <lay-form-item label="识别码KEY"  class="_row_style">
          <lay-input v-model="formData.key"></lay-input>
      </lay-form-item>
    </uni-forms-item>

    <uni-forms-item name="remark">
      <lay-form-item label="备注信息" class="_row_style">
            <lay-textarea  v-model="formData.remark" style="width: 300px;" :resize="true"></lay-textarea>
      </lay-form-item>
    </uni-forms-item>

      <lay-form-item  class="_row_style" style="margin-top:40px">
        <lay-button @click="submit" type="normal">确认新增</lay-button>
        <lay-button @click="closeAll">取消关闭</lay-button>
      </lay-form-item>
    </uni-forms>
  </view>
</template>

<script>
  import {store} from '@/uni_modules/uni-id-pages/common/store.js'
  import { getAllMerchantList } from '@/utils/cloud.js'
  import { validator } from '../../js_sdk/validator/food-printer-list.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food-printer-list';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "merchant_id": store.userInfo.merchant_id,
        "sn": "",
        "key": "",
        "remark": "",
        "print_times": null,
        "success_times": null,
        "error_times": null
      }
      return {
        merchantList:[],

        formData,
        formOptions: {},
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    mounted() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      closeAll(){
        this.$emit(`manualClose`,`addComponent`)
      },

      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          res.merchant_id =  store.userInfo.merchant_id
          
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.$emit(`refreshData`)
          this.closeAll();
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
